#include <pthread.h>
#include "Protoclo.hpp"
#include "Sock.hpp"

static void Usige(string proc)
{
    cout << "Usige: " << proc << "prot" << endl;
    exit(1);
}

void *HandlerRequest(void *args)
{
    int sock = *(int *)args;
    delete (int *)args;
    pthread_detach(pthread_self()); // 分离线程，不用等
    char buffer[1024];
    request_t req;
    ssize_t s = read(sock, buffer, sizeof(buffer) - 1);
    if (s > 0)
    {
        buffer[s] = 0;
        cout << "get a new request: " << buffer << endl;
        string str = buffer;
        DeserializeRequset(str, req); // 拿到client的数据反序列化

        response_t resp = {0, 0};
        //处理数据
        switch (req._op)
        {
        case '+':
            resp._result = req._x + req._y;
            break;
        case '-':
            resp._result = req._x - req._y;
            break;
        case '*':
            resp._result = req._x * req._y;
            break;
        case '/':
            if (req._y == 0)
                resp._code = -1; // 代表除0
            else
                resp._result = req._x / req._y;
            break;
        case '%':
            if (req._y == 0)
                resp._code = -2; // 代表模0
            else
                resp._result = req._x % req._y;
            break;
        default:
            resp._code = -3; // 代表请求方法异常
            break;
        }
        cout << "request: " << req._x << req._op << req._y << endl;
        string send_string=SerializeResponse(resp);//处理好数据后响应回去给client
        write(sock,send_string.c_str(),send_string.size());
        cout<<"服务结束:"<<send_string<<endl;
    }
    close(sock); //关闭链接
}
int main(int argc, char *argv[])
{
    if (argc != 2)
        Usige(argv[0]);

    uint16_t port = atoi(argv[1]);
    int listen_sock = Sock::Socket();

    Sock::Bind(listen_sock, port);
    Sock::Listen(listen_sock);

    for (;;)
    {
        int sock = Sock::Accept(listen_sock);
        if (sock > 0)
        {
            cout << "get a new link client" << endl;
            int *pram = new int(sock); //用来传sock
            pthread_t tid;
            pthread_create(&tid, nullptr, HandlerRequest, pram);
        }
    }
    return 0;
}